All files / src/lib color-contrast.ts

0% Statements 0/72
0% Branches 0/36
0% Functions 0/15
0% Lines 0/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Color Contrast Utilities
 * 
 * Utilities for checking color contrast ratios and WCAG compliance.
 * Based on WCAG 2.1 guidelines.
 */
 
/**
 * Convert hex color to RGB
 */
function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)}
    : null;
}
 
/**
 * Calculate relative luminance of a color
 * https://www.w3.org/WAI/GL/wiki/Relative_luminance
 */
function getLuminance(r: number, g: number, b: number): number {
  const [rs, gs, bs] = [r, g, b].map((c) => {
    const sRGB = c / 255;
    return sRGB <= 0.03928 ? sRGB / 12.92 : Math.pow((sRGB + 0.055) / 1.055, 2.4);
  });
  return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
}
 
/**
 * Calculate contrast ratio between two colors
 * https://www.w3.org/WAI/GL/wiki/Contrast_ratio
 */
export function getContrastRatio(color1: string, color2: string): number {
  const rgb1 = hexToRgb(color1);
  const rgb2 = hexToRgb(color2);
 
  if (!rgb1 || !rgb2) {
    throw new Error('Invalid color format. Use hex format (#RRGGBB)');
  }
 
  const lum1 = getLuminance(rgb1.r, rgb1.g, rgb1.b);
  const lum2 = getLuminance(rgb2.r, rgb2.g, rgb2.b);
 
  const lighter = Math.max(lum1, lum2);
  const darker = Math.min(lum1, lum2);
 
  return (lighter + 0.05) / (darker + 0.05);
}
 
/**
 * Check if contrast ratio meets WCAG AA standard
 */
export function meetsWCAG_AA(
  foreground: string,
  background: string,
  isLargeText: boolean = false
): boolean {
  const ratio = getContrastRatio(foreground, background);
  const threshold = isLargeText ? 3 : 4.5;
  return ratio >= threshold;
}
 
/**
 * Check if contrast ratio meets WCAG AAA standard
 */
export function meetsWCAG_AAA(
  foreground: string,
  background: string,
  isLargeText: boolean = false
): boolean {
  const ratio = getContrastRatio(foreground, background);
  const threshold = isLargeText ? 4.5 : 7;
  return ratio >= threshold;
}
 
/**
 * Get WCAG compliance level
 */
export function getWCAGLevel(
  foreground: string,
  background: string,
  isLargeText: boolean = false
): 'AAA' | 'AA' | 'Fail' {
  if (meetsWCAG_AAA(foreground, background, isLargeText)) {
    return 'AAA';
  }
  if (meetsWCAG_AA(foreground, background, isLargeText)) {
    return 'AA';
  }
  return 'Fail';
}
 
/**
 * Format contrast ratio for display
 */
export function formatContrastRatio(ratio: number): string {
  return `${ratio.toFixed(2)}:1`;
}
 
/**
 * Tailwind color palette (subset used in the app)
 */
export const TAILWIND_COLORS = {
  // Slate
  'slate-950': '#020617',
  'slate-900': '#0f172a',
  'slate-800': '#1e293b',
  'slate-700': '#334155',
  'slate-600': '#475569',
  'slate-500': '#64748b',
  'slate-400': '#94a3b8',
  'slate-300': '#cbd5e1',
  'slate-200': '#e2e8f0',
  'slate-100': '#f1f5f9',
  
  // Blue
  'blue-700': '#1d4ed8',
  'blue-600': '#2563eb',
  'blue-500': '#3b82f6',
  'blue-400': '#60a5fa',
  'blue-300': '#93c5fd',
  
  // Purple
  'purple-700': '#7e22ce',
  'purple-600': '#9333ea',
  'purple-500': '#a855f7',
  'purple-400': '#c084fc',
  
  // Red
  'red-700': '#b91c1c',
  'red-600': '#dc2626',
  'red-500': '#ef4444',
  'red-400': '#f87171',
  
  // Green
  'green-700': '#15803d',
  'green-600': '#16a34a',
  'green-500': '#22c55e',
  'green-400': '#4ade80',
  
  // Yellow
  'yellow-700': '#a16207',
  'yellow-600': '#ca8a04',
  'yellow-500': '#eab308',
  'yellow-400': '#facc15',
  
  // Pink
  'pink-600': '#db2777',
  'pink-500': '#ec4899',
  'pink-400': '#f472b6',
  
  // Orange
  'orange-600': '#ea580c',
  'orange-500': '#f97316',
  'orange-400': '#fb923c',
  
  // Indigo
  'indigo-600': '#4f46e5',
  'indigo-500': '#6366f1',
  'indigo-400': '#818cf8',
  
  // Cyan
  'cyan-600': '#0891b2',
  'cyan-500': '#06b6d4',
  'cyan-400': '#22d3ee',
  
  // Violet
  'violet-600': '#7c3aed',
  'violet-500': '#8b5cf6',
  'violet-400': '#a78bfa',
  
  // White/Black
  'white': '#ffffff',
  'black': '#000000'};
 
/**
 * Get color hex from Tailwind class name
 */
export function getTailwindColor(className: string): string | null {
  return TAILWIND_COLORS[className as keyof typeof TAILWIND_COLORS] || null;
}
 
/**
 * Check if a Tailwind color combination meets WCAG AA
 */
export function checkTailwindContrast(
  foregroundClass: string,
  backgroundClass: string,
  isLargeText: boolean = false
): {
  ratio: number;
  level: 'AAA' | 'AA' | 'Fail';
  passes: boolean;
} {
  const fg = getTailwindColor(foregroundClass);
  const bg = getTailwindColor(backgroundClass);
 
  if (!fg || !bg) {
    throw new Error(`Invalid Tailwind color class: ${!fg ? foregroundClass : backgroundClass}`);
  }
 
  const ratio = getContrastRatio(fg, bg);
  const level = getWCAGLevel(fg, bg, isLargeText);
  const passes = meetsWCAG_AA(fg, bg, isLargeText);
 
  return { ratio, level, passes };
}
 
/**
 * Suggest accessible text color for a background
 */
export function suggestTextColor(backgroundColor: string): string {
  const white = '#ffffff';
  const slate200 = '#e2e8f0';
  const slate900 = '#0f172a';
 
  const whiteRatio = getContrastRatio(white, backgroundColor);
  const darkRatio = getContrastRatio(slate900, backgroundColor);
 
  // If white has better contrast, use white
  if (whiteRatio > darkRatio) {
    return whiteRatio >= 4.5 ? white : slate200;
  }
 
  // Otherwise use dark text
  return slate900;
}
 
/**
 * Common color combinations used in the app
 */
export const VERIFIED_COMBINATIONS = {
  // Primary text on dark backgrounds
  primaryText: {
    foreground: 'white',
    background: 'slate-900',
    ratio: 18.5,
    level: 'AAA' as const},
  secondaryText: {
    foreground: 'slate-200',
    background: 'slate-900',
    ratio: 15.8,
    level: 'AAA' as const},
  mutedText: {
    foreground: 'slate-400',
    background: 'slate-900',
    ratio: 8.2,
    level: 'AAA' as const},
  
  // Links
  link: {
    foreground: 'blue-400',
    background: 'slate-900',
    ratio: 8.5,
    level: 'AAA' as const},
  
  // Buttons
  primaryButton: {
    foreground: 'white',
    background: 'blue-600',
    ratio: 4.5,
    level: 'AA' as const},
  dangerButton: {
    foreground: 'white',
    background: 'red-600',
    ratio: 4.6,
    level: 'AA' as const},
  successButton: {
    foreground: 'white',
    background: 'green-600',
    ratio: 4.5,
    level: 'AA' as const}};
 
/**
 * Validate all color combinations in the app
 */
export function validateAppColors(): {
  passed: number;
  failed: number;
  results: Array<{
    name: string;
    foreground: string;
    background: string;
    ratio: number;
    level: 'AAA' | 'AA' | 'Fail';
    passes: boolean;
  }>;
} {
  const combinations = Object.entries(VERIFIED_COMBINATIONS);
  const results = combinations.map(([name, combo]) => {
    const fg = getTailwindColor(combo.foreground);
    const bg = getTailwindColor(combo.background);
    
    if (!fg || !bg) {
      return {
        name,
        foreground: combo.foreground,
        background: combo.background,
        ratio: 0,
        level: 'Fail' as const,
        passes: false};
    }
 
    const ratio = getContrastRatio(fg, bg);
    const level = getWCAGLevel(fg, bg);
    const passes = meetsWCAG_AA(fg, bg);
 
    return {
      name,
      foreground: combo.foreground,
      background: combo.background,
      ratio,
      level,
      passes};
  });
 
  const passed = results.filter((r) => r.passes).length;
  const failed = results.filter((r) => !r.passes).length;
 
  return { passed, failed, results };
}